package com.leetcode.Offer;

public class JZ52 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        //两个指针，分别指向两个链表头部
        //到达末端再转移到另一个链表头部
        //两个指针相遇
        if (headA == null || headB == null) {
            return null;
        }

        ListNode a = headA;
        ListNode b = headB;
        int count = 0;
        while (a != b) {
            if (a == null) {
                count++;
                a = headB;
            } else {
                a = a.next;
            }
            if (b == null) {
                b = headA;
            } else {
                b = b.next;
            }
        }
        return a;
    }

    public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode n1 = headA;
        ListNode n2 = headB;

        while (n1 != n2) {
            n1 = n1 == null ? headB : n1.next;
            n2 = n2 == null ? headA : n2.next;
        }
        return n1;
    }
}
